<template>
  <base-breadcrumb>
    <a-card>
      <AuditBusinessDetail></AuditBusinessDetail> 
      <title-name title="施组(方案)打分表" />
      <div class="title">
        否决项
      </div>
      <a-table :columns="columns" :data-source="tableData" bordered :pagination="false">
        <!-- CheckBox选择框 -->
        <template slot="checkbox" slot-scope="text, record">
          <a-checkbox @change="changeCheckbox(record)" />
        </template>
        <!-- 序号 -->
        <span slot="serial" slot-scope="text, record, index">{{ index + 1 }}</span>
      </a-table>
      <div class="title">
        评分项
      </div>
      <a-table :columns="columnsScore" :data-source="ScoreTableData" bordered :pagination="false">
        <!-- 序号 -->
        <span slot="serial" slot-scope="text, record, index">{{ index + 1 }}</span>
        <template slot="score" slot-scope="text, record">
          <!-- <a @click="editScore(record)">评分</a> -->
          <BaseInputNumber
            v-model="record.score"
            style="width: 100px"
            :max="getMaxValue(record)"
            :precision="1"
            :min="0"
            placeholder="请评分"
            @blur="changeScore()"
          />
        </template>
        <template slot="information" slot-scope="text, record">
          <!-- <a @click="editScore(record)">评分</a> -->
          <BaseInput v-model="record.information" placeholder="请输入评分说明" type="textarea" />
        </template>
      </a-table>
      <div class="title">
        审核结果
      </div>
      <a-form-model
        :label-col="{ lg: { span: 6 }, sm: { span: 6 } }"
        :wrapper-col="{ lg: { span: 18 }, sm: { span: 18 } }"
      >
        <a-row>
          <a-col :md="8" :sm="8">
            <a-form-model-item label="审核总分">
              <BaseInput v-model="totalScore" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-model-item label="审核结果">
              <BaseInput v-model="result" disabled />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :md="16" :sm="16">
            <a-form-model-item label="其他评审意见">
              <BaseTextarea v-model="form.opinion" placeholder="请输入" :maxLength="700" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
      <div class="footer">
        <a-button type="primary" :loading="loading.isSubmit" @click="submitScoreForm(save)">
          提交审核结果
        </a-button>
        <!-- <a-button type="primary"  @click="saveSubmit()">提交</a-button> -->
        <a-button type="primary" @click="goBack">
          关闭
        </a-button>
      </div>
    </a-card>
  </base-breadcrumb>
</template>

<script>
import SelectTreeSubItem from '@/components/Select/SelectTreeSubItem'
import SelectPersonByProject from '@/components/Select/SelectPersonByProject'
import UploadList from '@/components/UploadList'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 项目
import TitleName from '@/components/TitleName/index.vue'
import { getOption, addList, editList, deleteList, getDetails } from '@/api/technical/approval'
import { listOption } from '@/api/technical/approvalPlan'
import { getProcessNodeList, completeTask } from '@/api/process'
import { submitConstructionScoreForm } from '@/api/design/designManage'
import Vue from 'vue'
import moment from 'moment'
import fileTable from './fileTable.vue'
import AuditBusinessDetail from '@/views/matters/AuditBusinessDetail'
export default {
  name: 'a' + Date.now(),
  components: {
    TitleName,
    SelectSubCompany,
    SelectProject,
    UploadList,
    SelectPersonByProject,
    fileTable,
    SelectTreeSubItem,
    AuditBusinessDetail
  },
  data() {
    const validReportType = (rule, value, callback) => {
      const validKey = this.form.reportingType === '1' ? 'programTypeId' : 'planSelection'
      if (!this.form[validKey]) {
        callback(new Error('请选择'))
      } else {
        callback()
      }
    }
    return {
      loading: {
        isDraft: false,
        isSubmit: false
      },
      form: {
        reportingType: '0',
        compiler: '',
        branchComId: '',
        projectId: '',
        fileInfoVOList: [],
        programTypeId: '',
        basicInformationDTOS: []
      },
      rules: {
        branchComId: [{ required: true, message: '请选择', trigger: 'change' }],
        projectId: [{ required: true, message: '请选择', trigger: 'change' }],
        reportingType: [{ required: true, message: '请选择', trigger: 'change' }],
        planSelection: [{ validator: validReportType, trigger: 'change' }],
        programTypeId: [{ validator: validReportType, trigger: 'change' }],
        currentVersion: [{ required: true, message: '请输入', trigger: 'change' }],
        reviewCode: [{ required: true, message: '请输入', trigger: 'change' }],
        fileCode: [{ required: true, message: '请输入', trigger: 'change' }],
        compiler: [{ required: true, message: '请选择', trigger: 'change' }],
        programOverview: [{ required: true, message: '请输入', trigger: 'change' }],
        bodyPages: [{ required: true, message: '请输入', trigger: 'change' }],
        attachmentPages: [{ required: true, message: '请输入', trigger: 'change' }]
      },
      planItemList: [], // 计划项列表
      type: '',
      id: '',
      disabled: false,
      typeOption: [],
      tableData: [],
      ScoreTableData: [],
      selectedRowKeys: '',
      selectedRows: '',
      totalScore: 100,
      result: '优秀',
      vetoHeaderId: '',
      columnsScore: [],
      columns: [],
      scoreInformation: '',
      scorecount: '',
      vetoList: [],
      // formDatas: {},
      approveInfos: [], // 审批流程信息
      procInstId: '', //当前流程实例ID
      taskId: '', //当前流程节点ID
      processName: '', //流程名称
      taskName: '', //当前流程节点名称
      taskDefKey: '', //任务标识
      currentTime: '', //当前审批时间
      currentUser: '', //当前审批人
      flowRequesting: false,
      detailUrl: null, //详情地址

      assignType: '', //节点类型   0 变量获取 1 处理人 2 候选人 3 候选组 4 会签
      assignCode: '', //候选组编码 岗位编码
      assignLevel: '', //层级 项目部 PD 分公司 BC 公司 CO
      businessType: '', //业务类型 0 项目,

      conclusionData: []
    }
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        selectedRows: this.selectedRows, // 当前行所有数据
        onChange: this.onSelectChange
      }
    }
  },

  created() {
    this.form.user = JSON.parse(sessionStorage.getItem('ycloud-user_info')).username
    this.id = this.$route.query.id
    this.getDetails()
    this.clickTypeOption()
    const {
      type,
      code,
      level,
      btype,
      businessId,
      procInstId,
      name,
      processName,
      detailUrl,
      taskId,
      taskDefKey
    } = this.$route.query
    if (type) {
      this.assignType = type
      this.assignCode = code
      this.assignLevel = level
      this.businessType = btype
    }
    this.id = businessId
    if (!this.id) {
      this.$error({ content: '无指定业务ID，将自动关闭' })
      setTimeout(() => {
        window.close()
      }, 1500)
      return
    }
    this.procInstId = procInstId
    this.currentUser = Vue.getAcloudProvider().getUserInfo()
    this.taskName = decodeURIComponent(name)
    this.processName = decodeURIComponent(processName)
    document.title = this.processName + '-' + this.taskName
    if (detailUrl) {
      this.detailUrl = decodeURIComponent(detailUrl)
    }
    this.taskId = taskId
    this.taskDefKey = taskDefKey
    this.currentTime = moment().format('yyyy-MM-DD HH:mm')

    //获取流程节点执行情况
    // this.getProcessNodes()
  },
  methods: {
    // 获取输入项的最大允许值
    getMaxValue(data) {
      const targetData = this.columnsScore.find(item => item.code === '4') // 考核评分列
      return (targetData && Number(data[targetData['dataIndex']])) || 0
    },
    handleProjectChanged() {
      this.getOption()
    },
    handleFileUploaded(list) {
      this.form.fileInfoVOList = [...list]
    },
    handleClose() {
      this.$close()
    },
    listOption() {
      listOption({ type: '5' }).then(res => {
        this.typeOption = res.data
      })
      listOption({ type: '8' }).then(res => {
        this.conclusionData = res.data
      })
    },
    clickTypeOption() {
      this.listOption()
    },
    getOption() {
      const { projectId } = this.form
      if (!projectId) return
      const params = {
        projectId: projectId
      }
      getOption(params).then(res => {
        if (res.code === 200) {
          this.planItemList = res.data
        }
      })
    },

    initTable(res) {
      // 否决项
      this.columns = res.data.vetoHeader
      this.tableData = res.data.vetoContent
      this.columns.unshift({
        dataIndex: 'serial',
        formId: null,
        title: '序号',
        code: '0',
        sort: 0,
        inputType: null,
        scopedSlots: { customRender: 'serial' }
      })
      let obj = {}
      this.columns.forEach(item => {
        obj = this.columns.filter(items => items.code == '9')
      })
      console.log(obj)
      this.vetoHeaderId = obj[0].dataIndex
      obj[0].scopedSlots = { customRender: 'checkbox' }
      console.log(this.columns)

      this.columnsScore = res.data.scoreHeader
      this.ScoreTableData = res.data.scoreContent
      // this.formDatas = cloneDeep(res.data.scoreHeader)
      this.columnsScore.unshift({
        dataIndex: 'serial',
        formId: null,
        title: '序号',
        code: '0',
        sort: 0,
        inputType: null,
        scopedSlots: { customRender: 'serial' }
      })

      let objScore = {}
      this.columnsScore.forEach(item => {
        objScore = this.columnsScore.filter(items => items.code == '10')
      })
      objScore[0].scopedSlots = { customRender: 'score' }
      this.scorecount = objScore[0].dataIndex

      let information = {}
      this.columnsScore.forEach(item => {
        information = this.columnsScore.filter(items => items.code == '9')
      })
      information[0].scopedSlots = { customRender: 'information' }
      this.scoreInformation = information[0].dataIndex
    },
    submitScoreForm() {
      console.log(this.ScoreTableData)
      let arr = []
      this.ScoreTableData.forEach(item => {
        arr.push({
          id: item.id,

          scoreIns: item.information,
          scoreCont: item.score
        })
      })
      let newData = JSON.parse(JSON.stringify(arr).replace(/scoreIns/g, this.scoreInformation))
      let datas = JSON.parse(JSON.stringify(newData).replace(/scoreCont/g, this.scorecount))
      console.log(datas)
      this.contentList = datas
      let submitForm = []
      submitForm.push({
        id: this.form.id,
        vetoList: this.vetoList,
        contentList: this.contentList,
        opinion: this.form.opinion,
        totalScore: this.totalScore,
        result: this.result
      })
      this.loading.isSubmit = true
      submitConstructionScoreForm(submitForm[0]).then(res => {
        if (res.code === 200) {
          // console.log(this.totalScore < 60 || this.vetoList.length > 0)
          if (this.totalScore < 60 || this.vetoList.length > 0) {
            this.submit(true)
          } else {
            this.submit(false)
          }
        } else {
          this.$error({ content: '提交失败，请稍后重试' })
        }
        // if (res.code == '200') {
        //     this.$message.success('提交审核成功')
        //     this.$router.push('/project/design/plotsManage')
        // }
      })
    },
    getDetails() {
      if (this.id) {
        getDetails({ id: this.id }).then(res => {
          this.form = {
            ...this.form,
            ...res.data
          }
          this.form.programTypeId = res.data.programTypeId
          this.form.planSelection = res.data.planSelectionId
          this.form.whetherMajorExpense = res.data.whetherMajorExpense === 'true' ? true : false
          this.form.whetherProfessionalSubcontracting =
            res.data.whetherProfessionalSubcontracting === 'true' ? true : false
          this.$nextTick(() => {
            this.form.projectId = res.data.projectId
            this.getOption()
          })
          this.initTable(res)
        })
      }
    },
    goBack() {
      window.close()
    },
    changeCheckbox(record) {
      let list = []
      let obj = []
      let arr = []

      record.check = !record.check
      arr = this.tableData.filter(items => items.check == true)

      arr.forEach(item => {
        obj.push({
          id: item.id,
          ids: '是'
        })
      })
      let newdata = JSON.parse(JSON.stringify(obj).replace(/ids/g, this.vetoHeaderId))
      this.vetoList = newdata
      console.log(this.vetoList)
    },
    changeScore(value) {
      let arr = []
      let obj = 2
      this.ScoreTableData.forEach(item => {
        console.log(item.score)
        if (item.score) {
          arr.push(parseFloat(item.score))
        }
      })
      console.log(arr)
      console.log(obj)

      this.totalScore = arr.length > 0 ? (this.totalScore = 100 - eval(arr.join('+'))) : 100

      console.log(this.totalScore)
      if (this.totalScore < 70) {
        this.result = '不合格'
      } else if (this.totalScore >= 70 && this.totalScore < 80) {
        this.result = '合格'
      } else if (this.totalScore >= 80 && this.totalScore < 90) {
        this.result = '良好'
      } else if (this.totalScore >= 90) {
        this.result = '优秀'
      }
    },
    onSelectChange(selectedRowKeys) {
      console.log('selectedRowKeys changed: ', selectedRowKeys)
      this.selectedRowKeys = selectedRowKeys
    },
    notifyParent() {
      window.opener.postMessage('finish', window.location.origin)
    },
    submit(reject) {
      const data = {
        formData: {
          opinions: this.form.opinion,
          reject,
          projectId: ''
        },
        assignTypeEnum: this.assignType, //指派类型
        assgins: this.form.respEmployeeId, //人员
        groupEnum: this.form.jobsSelectedName, //岗位
        procInstId: this.procInstId,
        taskId: this.taskId,
        userId: this.currentUser.id
      }
      console.log(data)
      const variable = {}
      // return;
      if (reject) {
        variable.reject = true
      }

      data.variables = {
        ...variable
        // ...this.submitData, // 特殊流程的数据，转交给审批
      }

      return completeTask(data)
        .then(res => {
          this.loading.isSubmit = false
          if (res.status === 200) {
            this.notifyParent() // 通知父窗口
            // this.$success({
            //   content: '审批提交成功，即将自动关闭当前窗口',
            //   onOk() {
                window.close()
            //   }
            // })
            // setTimeout(() => {
            //   window.close()
            // }, 2000)
          } else {
            this.$error({ content: '审批提交失败，请稍后重试' })
          }
          // return res
        })
        .catch(err => {
          this.loading.isSubmit = false
          // return err
        })
    }
  }
}
</script>

<style lang="less">
.foot-btn {
  display: flex;
  justify-content: flex-end;
}
.radio-box {
  .ant-radio-wrapper {
    position: static !important;
  }
  .ant-radio-group {
    margin-top: 3% !important;
    display: flex;
  }
}
.input {
  width: 100%;
}
.footer {
  float: right;
  margin-right: 10px;
}
.footer button {
  margin-left: 10px;
}
.title {
  border-left: 4px solid #1890ff;
  font-weight: bold;
  font-size: 14px;
  margin-bottom: 20px;
  padding-left: 10px;
  height: 18px;
  line-height: 20px;
  margin-left: 20px;
  margin-top: 20px;
}
.customtable {
  width: 100%;
  border: 1px solid gainsboro;

  thead {
    background: rgb(244, 244, 244);

    th {
      padding: 10px;
      border: 1px solid gainsboro;
    }
  }

  tbody {
    td {
      padding: 10px;
      border: 1px solid gainsboro;
    }
  }
}
</style>
